<template>
	<view class="container">
		<view class="page-header">
			<text class="page-title">{{ projectTitle }}</text>
			<view class="project-details" v-if="projectData">
				<text class="detail-item">样品类型: {{ projectData.sampleType }}</text>
				<text class="detail-item">液体种类: {{ projectData.liquidType }}</text>
				<text class="detail-item" v-if="projectData.notes">备注: {{ projectData.notes }}</text>
			</view>
		</view>
		
		<view class="content-container">
			<!-- 图像显示区域 -->
			<view class="image-container">
				<image v-if="imagePath" class="preview-image" :src="imagePath" mode="aspectFit"></image>
				<view v-else class="no-image">
					<text class="no-image-text">暂无图像，请点击下方拍照按钮</text>
				</view>
			</view>
			
			<!-- 分析结果展示区域 -->
			<view class="analysis-results" v-if="projectData && projectData.analysisResults && projectData.analysisResults.length > 0">
				<view class="analysis-title">
					<text>分析结果</text>
				</view>
				<view class="result-item" v-for="(result, index) in projectData.analysisResults" :key="index">
					<view class="result-header">
						<text class="result-type">{{result.type}}</text>
						<text class="result-date">{{formatDate(result.date)}}</text>
					</view>
					<view class="result-content">
						<view class="result-data" v-for="(value, key) in result.data" :key="key">
							<text class="data-label">{{formatLabel(key)}}: </text>
							<text class="data-value">{{formatValue(value)}}</text>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 操作按钮区域 -->
			<view class="actions-container">
				<view class="action-btn camera-btn" @click="handleTakePhoto">
					<text class="action-icon">📷</text>
					<text class="action-text">拍照</text>
				</view>
				
				<view v-if="imagePath" class="action-btn retake-btn" @click="handleTakePhoto">
					<text class="action-icon">🔄</text>
					<text class="action-text">重拍</text>
				</view>
				
				<view v-if="imagePath" class="action-btn analyze-btn" @click="showAnalysisOptions">
					<text class="action-icon">📊</text>
					<text class="action-text">分析</text>
				</view>
			</view>
		</view>
		
		<!-- 分析选项对话框 -->
		<view v-if="showAnalysisDialog" class="dialog-mask" @click="hideAnalysisDialog">
			<view class="dialog-container" @click.stop>
				<view class="dialog-header">
					<text class="dialog-title">选择分析方式</text>
				</view>
				<view class="dialog-content">
					<!-- <view class="analysis-option" @click="handleContourAnalysis">
						<text class="option-icon">🔍</text>
						<view class="option-info">
							<text class="option-title">轮廓检测</text>
							<text class="option-desc">分析液滴轮廓形状特征</text>
						</view>
					</view> -->
					<view class="analysis-option" @click="handleTensionAnalysis">
						<text class="option-icon">⚖️</text>
						<view class="option-info">
							<text class="option-title">张力计算</text>
							<text class="option-desc">计算液滴表面张力数据</text>
						</view>
					</view>
					<view class="analysis-option" @click="handleContactAngleAnalysis">
						<text class="option-icon">📐</text>
						<view class="option-info">
							<text class="option-title">接触角计算</text>
							<text class="option-desc">测量液滴与表面的接触角</text>
						</view>
					</view>
				</view>
				<view class="dialog-footer">
					<button class="dialog-cancel-btn" @click="hideAnalysisDialog">取消</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { ref, onMounted } from 'vue'

// 获取页面参数
const projectId = ref(0)
const projectTitle = ref('项目详情')
const projectData = ref(null)

// 图像路径
const imagePath = ref('')

// 页面加载
// onMounted(() => {
	
// })

onLoad((params) => {
	// 直接使用onLoad传入的参数
	if (params) {
		console.log('参数ID:', params.id)
		projectId.value = params.id || '0'
		projectTitle.value = params.title || '项目详情'
		
		// 从本地存储获取项目数据
		loadProjectData()
	} else {
		// 尝试通过getCurrentPages获取
		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		const options = currentPage?.$page?.options
		
		if (options) {
			console.log('通过getCurrentPages获取参数ID:', options.id)
			projectId.value = options.id || '0'
			projectTitle.value = options.title || '项目详情'
			
			// 从本地存储获取项目数据
			loadProjectData()
		} else {
			console.error('无法获取页面参数')
			uni.showToast({
				title: '加载失败，参数错误',
				icon: 'none',
				complete: () => {
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				}
			})
		}
	}
	
	// 监听分析结果事件
	uni.$on('analysisComplete', handleAnalysisComplete)
})

// 监听分析结果
const handleAnalysisComplete = (data) => {
	if (data && data.projectId === projectId.value) {
		// 更新项目数据中的分析结果
		addAnalysisResult(data.type, data.result)
		// 重新加载项目数据
		loadProjectData()
	}
}

// 添加分析结果
const addAnalysisResult = (type, resultData) => {
	// 获取项目列表
	const projectList = uni.getStorageSync('projectList') || []
	// 查找当前项目
	const index = projectList.findIndex(item => item.id === projectId.value)
	
	if (index !== -1) {
		// 如果项目存在
		if (!projectList[index].analysisResults) {
			projectList[index].analysisResults = []
		}
		
		// 添加新的分析结果
		projectList[index].analysisResults.push({
			type: type,
			date: new Date().toISOString(),
			data: resultData,
			imagePath: imagePath.value // 保存关联的图像路径
		})
		
		// 更新存储
		uni.setStorageSync('projectList', projectList)
	}
}

// 加载项目数据
const loadProjectData = () => {
	const projectList = uni.getStorageSync('projectList') || []
	const project = projectList.find(item => item.id === projectId.value)
	
	if (project) {
		projectData.value = project
		projectTitle.value = project.title
		
		// 如果项目有保存的图像路径，则显示
		if (project.lastImagePath) {
			imagePath.value = project.lastImagePath
		}
	} else {
		uni.showToast({
			title: '项目不存在',
			icon: 'none',
			complete: () => {
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			}
		})
	}
}

// 拍照处理
const handleTakePhoto = () => {
	uni.chooseImage({
		count: 1,
		sourceType: ['camera'],
		success: (res) => {
			imagePath.value = res.tempFilePaths[0]
			
			// 将图像路径保存到项目中
			saveImagePath(res.tempFilePaths[0])
			
			// 显示拍照成功提示
			uni.showToast({
				title: '拍照成功',
				icon: 'success'
			})
		},
		fail: (err) => {
			console.error('拍照失败', err)
			uni.showToast({
				title: '拍照失败',
				icon: 'none'
			})
		}
	})
}

// 保存图像路径到项目
const saveImagePath = (path) => {
	const projectList = uni.getStorageSync('projectList') || []
	const index = projectList.findIndex(item => item.id === projectId.value)
	
	if (index !== -1) {
		projectList[index].lastImagePath = path
		uni.setStorageSync('projectList', projectList)
	}
}

// 显示分析选项对话框
const showAnalysisOptions = () => {
	if (!imagePath.value) {
		uni.showToast({
			title: '请先拍摄图像',
			icon: 'none'
		})
		return
	}
	
	showAnalysisDialog.value = true
}

// 分析选项对话框
const showAnalysisDialog = ref(false)
const hideAnalysisDialog = () => {
	showAnalysisDialog.value = false
}

// 轮廓检测分析
const handleContourAnalysis = () => {
	hideAnalysisDialog()
	
	// 保存图像路径到全局变量或缓存中
	uni.setStorageSync('analyzedImagePath', imagePath.value)
	// 保存当前项目ID
	uni.setStorageSync('currentProjectId', projectId.value)
	
	// 跳转到轮廓检测页面
	uni.navigateTo({
		url: '/pages/opendrop/opendrop'
	})
}

// 张力计算分析
const handleTensionAnalysis = () => {
	hideAnalysisDialog()
	
	// 显示加载中提示
	uni.showLoading({
		title: '正在准备...'
	})
	
	// 保存图像路径到全局变量或缓存中
	uni.setStorageSync('analyzedImagePath', imagePath.value)
	// 保存当前项目ID
	uni.setStorageSync('currentProjectId', projectId.value)
	
	// 延迟后再跳转，减轻加载负担，避免闪烁
	setTimeout(() => {
		// 隐藏加载提示
		uni.hideLoading()
		
		// 跳转到张力计算页面
		uni.navigateTo({
			url: '/pages/droppy/droppy',
			animationType: 'slide-in-right', // 使用向右滑入动画
			animationDuration: 300 // 设置动画时长
		})
	}, 300) // 300ms延迟
}

// 接触角计算分析
const handleContactAngleAnalysis = () => {
	hideAnalysisDialog()
	
	// 保存图像路径到全局变量或缓存中
	uni.setStorageSync('analyzedImagePath', imagePath.value)
	// 保存当前项目ID
	uni.setStorageSync('currentProjectId', projectId.value)
	
	// 跳转到接触角计算页面
	uni.navigateTo({
		url: '/pages/image/image'
	})
}

// 格式化日期
const formatDate = (dateString) => {
	const date = new Date(dateString)
	return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 格式化标签
const formatLabel = (key) => {
	// 将驼峰命名或下划线转换为空格分隔的标签
	return key.replace(/([A-Z])/g, ' $1')
		.replace(/_/g, ' ')
		.replace(/^\w/, c => c.toUpperCase()) // 首字母大写
}

// 格式化数值
const formatValue = (value) => {
	if (typeof value === 'number') {
		return value.toFixed(2)
	}
	return value
}
</script>

<style>
.container {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding: 30rpx;
	display: flex;
	flex-direction: column;
}

.page-header {
	margin-bottom: 40rpx;
}

.page-title {
	font-size: 40rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 20rpx;
}

.project-details {
	display: flex;
	flex-direction: column;
	gap: 10rpx;
	background-color: #f8f8f8;
	padding: 20rpx;
	border-radius: 10rpx;
	margin-top: 10rpx;
}

.detail-item {
	font-size: 28rpx;
	color: #666;
}

.content-container {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 40rpx;
}

.image-container {
	height: 750rpx;
	background-color: #fff;
	border-radius: 12rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	display: flex;
	justify-content: center;
	align-items: center;
}

.preview-image {
	width: 100%;
	height: 100%;
}

.no-image {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	height: 100%;
	padding: 40rpx;
}

.no-image-text {
	font-size: 28rpx;
	color: #999;
	text-align: center;
}

/* 分析结果展示区域样式 */
.analysis-results {
	background-color: #fff;
	border-radius: 12rpx;
	overflow: hidden;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	padding: 20rpx;
}

.analysis-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 20rpx;
	padding-bottom: 10rpx;
	border-bottom: 1px solid #f0f0f0;
}

.result-item {
	background-color: #f9f9f9;
	border-radius: 8rpx;
	padding: 16rpx;
	margin-bottom: 16rpx;
}

.result-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 12rpx;
}

.result-type {
	font-size: 28rpx;
	font-weight: 600;
	color: #1890ff;
}

.result-date {
	font-size: 24rpx;
	color: #999;
}

.result-content {
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.result-data {
	display: flex;
}

.data-label {
	font-size: 26rpx;
	color: #666;
	width: 180rpx;
}

.data-value {
	font-size: 26rpx;
	color: #333;
	font-weight: 500;
}

.actions-container {
	display: flex;
	justify-content: center;
	gap: 40rpx;
	margin-top: 20rpx;
}

.action-btn {
	width: 160rpx;
	height: 160rpx;
	border-radius: 20rpx;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.action-icon {
	font-size: 56rpx;
	margin-bottom: 10rpx;
}

.action-text {
	font-size: 28rpx;
	color: #333;
}

.camera-btn {
	background-color: #1890ff;
}

.camera-btn .action-icon,
.camera-btn .action-text {
	color: #fff;
}

.retake-btn {
	background-color: #fff;
}

.analyze-btn {
	background-color: #52c41a;
}

.analyze-btn .action-icon,
.analyze-btn .action-text {
	color: #fff;
}

.dialog-mask {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	justify-content: center;
	align-items: center;
}

.dialog-container {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 40rpx;
	width: 80%;
	max-width: 600rpx;
}

.dialog-header {
	margin-bottom: 40rpx;
}

.dialog-title {
	font-size: 40rpx;
	font-weight: 600;
	color: #333;
}

.dialog-content {
	margin-bottom: 40rpx;
}

.analysis-option {
	display: flex;
	align-items: center;
	padding: 20rpx;
	border-bottom: 1rpx solid #eee;
}

.option-icon {
	font-size: 56rpx;
	margin-right: 20rpx;
}

.option-info {
	flex: 1;
}

.option-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 10rpx;
}

.option-desc {
	font-size: 28rpx;
	color: #999;
}

.dialog-footer {
	display: flex;
	justify-content: flex-end;
}

.dialog-cancel-btn {
	padding: 10rpx 20rpx;
	border: none;
	border-radius: 10rpx;
	background-color: #1890ff;
	color: #fff;
	font-size: 28rpx;
	cursor: pointer;
}
</style>
